#include<zmq.hpp>
#include<cstdlib>
#include<assert.h>
#include<string>
#include<ctime>
#include<unordered_set>
#include<unordered_map>
#include<iostream>
#include<queue>
#include<mutex>
#include<thread>
#include<condition_variable>
#include<chrono>
using namespace std;
struct user{
   int uid;
  string nickname;
  string pwd;
  chrono::high_resolution_clock::time_point lasttime;
};
struct sigmsg{
   char flag;
   int uid;
   char nickname[8];
   char pwd[8];
};
struct result_code{
   int code;
   char msg[20];
};
struct message{
   int chatid; // 目标聊天室；
   int uid; // 发送者id
   char m_msg[1024];

};
const int MaxSize =200;
const int MaxWait =180;
mutex queMtx;
condition_variable NotFull,NotEmpty;
queue<message> taskQue;
unordered_set<string> ust;
vector<user> users;
//unordered_map<int,unordered_set<user,[](user &u)->size_t{return hash<int>(u.uid);},
// [](user &lu,user & ru)->bool{return lu.uid==ru.uid;}>>
unordered_map<int,vector<user>> chatroom;
void taskfun(){
/* 每轮开始，遍历一个链表或者最小堆来摘掉聊天室里面超时的用户；  
 最小堆 prority_queue<user,vector<int>,[](user&lr,user&ru)->bool{return lu.lasttime>}>  
 */
      {
         unique_lock<mutex>(queMtx);
      /* 
      设计的思路是根据队列的消息给对应聊天室的所有成员发送消息
      
      
      
       */
   }
}
void submit(message &msg){
   
   {
      unique_lock<mutex>(queMtx);
      if(!NotFull.wait_for(queMtx,chrono::seconds(1),
      []()->bool{return taskQue.size()<MaxSize;})){
         cerr<<"消息未提交"<<msg.uid<<"发向聊天室"<<msg.chatid<<endl;
      return; // 提前结束；
      }
      taskQue.emplace(msg);
      NotEmpty.notify_all();
   }

}


int main(){

 void * ctx = zmq_ctx_new();
 void *responder = zmq_socket(ctx,ZMQ_REP);
 int rc = zmq_bind(responder,"tcp://127.0.0.1:8888");
 assert(rc==0);
 sigmsg mg;
 while(1){
   memset(&mg,0x00,sizeof(mg));
   zmq_recv(responder,&mg,sizeof(mg),0);
   user u;
   result_code rt;
   std::cout<<"收到"<<mg.flag<<" "<<mg.nickname<<" "<<mg.pwd<<std::endl;
   switch(mg.flag){
      case '0':
      // 开始注册；
      u.uid=users.size();
      u.nickname =mg.nickname;
      u.pwd =mg.pwd;
      u.lasttime = chrono::high_resolution_clock().now(); 
       rt ={u.uid,"注册成功"};
      if(ust.find(u.nickname)!=ust.end()){
         rt.code=-1;
         memcpy(rt.msg,"用户已存在",sizeof("用户已存在"));
      }
      break;

      case '1':
       if(mg.uid<users.size()&&users[mg.uid].pwd==string(mg.pwd)){
            rt ={mg.uid,"登录成功"};
         
       }
       else rt={-1,"登录失败"};
      break;

   }
      
   zmq_send(responder,&rt,sizeof(rt),0);
 }
}